<template>
  <div class="markdown-editor-container">
    <el-card class="editor-card">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button-group class="format-buttons">
          <el-button @click="insertText('**', '**')" title="加粗">
            <icon icon="mdi:format-bold" />
          </el-button>
          <el-button @click="insertText('*', '*')" title="斜体">
            <icon icon="mdi:format-italic" />
          </el-button>
          <el-button @click="insertText('~~', '~~')" title="删除线">
            <icon icon="mdi:format-strikethrough" />
          </el-button>
          <el-button @click="insertText('# ', '')" title="一级标题">
            <span>H1</span>
          </el-button>
          <el-button @click="insertText('## ', '')" title="二级标题">
            <span>H2</span>
          </el-button>
          <el-button @click="insertText('### ', '')" title="三级标题">
            <span>H3</span>
          </el-button>
          <el-button @click="insertText('- ', '')" title="无序列表">
            <icon icon="mdi:format-list-bulleted" />
          </el-button>
          <el-button @click="insertText('1. ', '')" title="有序列表">
            <icon icon="mdi:format-list-numbered" />
          </el-button>
          <el-button @click="insertText('> ', '')" title="引用">
            <icon icon="mdi:format-quote-close" />
          </el-button>
          <el-button @click="insertText('```\n', '\n```')" title="代码块">
            <icon icon="mdi:code-braces" />
          </el-button>
          <el-button @click="insertText('`', '`')" title="行内代码">
            <icon icon="mdi:code-tags" />
          </el-button>
          <el-button @click="insertText('[', '](url)')" title="链接">
            <icon icon="mdi:link" />
          </el-button>
          <el-button @click="insertText('![', '](image-url)')" title="图片">
            <icon icon="mdi:image" />
          </el-button>
          <el-button @click="insertText('---\n', '')" title="分割线">
            <icon icon="mdi:minus" />
          </el-button>
        </el-button-group>

        <el-button-group class="action-buttons">
          <el-button type="primary" @click="saveDraft">
            <icon icon="mdi:content-save-edit" />
            保存草稿
          </el-button>
          <el-button type="success" @click="publishArticle">
            <icon icon="mdi:send" />
            发布文章
          </el-button>
          <el-button type="info" @click="clearContent">
            <icon icon="mdi:delete" />
            清空
          </el-button>
          <el-button @click="toggleDraftDrawer">
            <icon icon="mdi:bookmark" />
            草稿箱({{ drafts.length }})
          </el-button>
        </el-button-group>
      </div>

      <!-- 编辑和预览区域 -->
      <div class="editor-preview-container">
        <!-- 编辑区域 -->
        <div class="editor-area">
          <el-input
            v-model="content"
            type="textarea"
            :rows="20"
            resize="none"
            placeholder="请输入Markdown内容..."
            class="editor-input"
            ref="editorInput"
            @input="handleContentChange"
          ></el-input>
        </div>

        <!-- 预览区域 -->
        <div class="preview-area">
          <div class="preview" v-html="compiledMarkdown"></div>
        </div>
      </div>

      <!-- 字数统计 -->
      <div class="status-bar">
        <span>字数: {{ wordCount }}</span>
        <span>行数: {{ lineCount }}</span>
        <span>字符数: {{ charCount }}</span>
        <span v-if="lastSavedTime">最后保存: {{ lastSavedTime }}</span>
      </div>

      <!-- 草稿箱抽屉 -->
      <el-drawer
        v-model="draftDrawerVisible"
        title="草稿箱"
        direction="rtl"
        size="40%"
      >
        <div class="draft-list">
          <div
            v-for="(draft, index) in drafts"
            :key="index"
            class="draft-item"
            @click="loadDraft(draft)"
          >
            <div class="draft-title">
              {{ draft.title || '无标题草稿' }}
              <span class="draft-time">{{ formatTime(draft.time) }}</span>
            </div>
            <div class="draft-preview">{{ draft.content.substring(0, 100) }}...</div>
            <div class="draft-actions">
              <el-button
                type="danger"
                size="small"
                @click.stop="deleteDraft(index)"
                circle
              >
                <icon icon="mdi:delete" />
              </el-button>
            </div>
          </div>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { Icon } from '@iconify/vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 配置marked
marked.setOptions({
  breaks: true,
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(lang, code).value
    }
    return hljs.highlightAuto(code).value
  }
})

// 编辑器内容
const content = ref('')
const editorInput = ref(null)
const draftDrawerVisible = ref(false)
const lastSavedTime = ref('')
const autoSaveTimer = ref(null)
const drafts = ref([])

// 从本地存储加载草稿
onMounted(() => {
  const savedDrafts = localStorage.getItem('markdown-drafts')
  if (savedDrafts) {
    drafts.value = JSON.parse(savedDrafts)
  }

  // 设置自动保存定时器
  autoSaveTimer.value = setInterval(() => {
    if (content.value.trim()) {
      autoSaveDraft()
    }
  }, 30000) // 每30秒自动保存一次
})

// 计算属性
const compiledMarkdown = computed(() => {
  return DOMPurify.sanitize(marked(content.value))
})

const wordCount = computed(() => {
  return content.value.trim() ? content.value.trim().split(/\s+/).length : 0
})

const lineCount = computed(() => {
  return content.value ? content.value.split('\n').length : 0
})

const charCount = computed(() => {
  return content.value.length
})

// 方法
const insertText = (prefix, suffix) => {
  const textarea = editorInput.value?.textarea
  if (!textarea) return

  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = content.value.substring(start, end)

  content.value =
    content.value.substring(0, start) +
    prefix + selectedText + suffix +
    content.value.substring(end)

  // 重新设置光标位置
  const newCursorPos = start + prefix.length
  setTimeout(() => {
    textarea.setSelectionRange(newCursorPos, newCursorPos + selectedText.length)
    textarea.focus()
  }, 0)
}

const handleContentChange = () => {
  // 内容变化时触发的逻辑
  updateLastSavedTime()
}

const updateLastSavedTime = () => {
  const now = new Date()
  lastSavedTime.value = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`
}

const saveDraft = () => {
  if (!content.value.trim()) {
    ElMessage.warning('内容不能为空')
    return
  }

  ElMessageBox.prompt('请输入草稿标题', '保存草稿', {
    confirmButtonText: '保存',
    cancelButtonText: '取消',
    inputPlaceholder: '我的草稿',
    inputValidator: (value) => {
      if (!value || value.trim().length < 2) {
        return '标题至少需要2个字符'
      }
      return true
    }
  }).then(({ value }) => {
    const newDraft = {
      title: value,
      content: content.value,
      time: new Date().getTime()
    }

    drafts.value.unshift(newDraft)
    saveDraftsToLocalStorage()
    ElMessage.success('草稿保存成功')
    updateLastSavedTime()
  }).catch(() => {})
}

const autoSaveDraft = () => {
  if (!content.value.trim()) return

  const existingAutoDraftIndex = drafts.value.findIndex(d => d.title === '自动保存')
  const newDraft = {
    title: '自动保存',
    content: content.value,
    time: new Date().getTime()
  }

  if (existingAutoDraftIndex >= 0) {
    drafts.value[existingAutoDraftIndex] = newDraft
  } else {
    drafts.value.unshift(newDraft)
  }

  saveDraftsToLocalStorage()
  updateLastSavedTime()
}

const saveDraftsToLocalStorage = () => {
  // 只保留最新的20个草稿
  if (drafts.value.length > 20) {
    drafts.value = drafts.value.slice(0, 20)
  }
  localStorage.setItem('markdown-drafts', JSON.stringify(drafts.value))
}

const loadDraft = (draft) => {
  content.value = draft.content
  draftDrawerVisible.value = false
  ElMessage.success('草稿已加载')
}

const deleteDraft = (index) => {
  ElMessageBox.confirm('确定要删除这个草稿吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    drafts.value.splice(index, 1)
    saveDraftsToLocalStorage()
    ElMessage.success('草稿已删除')
  }).catch(() => {})
}

const publishArticle = () => {
  if (!content.value.trim()) {
    ElMessage.warning('内容不能为空')
    return
  }

  ElMessageBox.confirm('确定要发布这篇文章吗?', '发布确认', {
    confirmButtonText: '发布',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    // 这里可以添加实际发布逻辑，比如调用API
    ElMessage.success('文章发布成功')

    // 发布后可以清空内容或保留
    // content.value = ''
  }).catch(() => {})
}

const clearContent = () => {
  ElMessageBox.confirm('确定要清空所有内容吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    content.value = ''
    ElMessage.success('已清空')
  }).catch(() => {})
}

const toggleDraftDrawer = () => {
  draftDrawerVisible.value = !draftDrawerVisible.value
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (autoSaveTimer.value) {
    clearInterval(autoSaveTimer.value)
  }
})
</script>

<style lang="scss">
.markdown-editor-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;

  .editor-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .toolbar {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;

      .format-buttons {
        flex-wrap: wrap;
        row-gap: 5px;
      }

      .action-buttons {
        margin-left: 10px;
      }

      .el-button {
        display: inline-flex;
        align-items: center;
        gap: 4px;
      }
    }

    .editor-preview-container {
      display: flex;
      gap: 20px;
      min-height: 600px;

      .editor-area {
        flex: 1;
        min-width: 0;

        .editor-input {
          font-family: 'Consolas', 'Monaco', monospace;
          font-size: 14px;
          line-height: 1.6;
          height: 100%;

          textarea {
            padding: 15px;
            height: 100% !important;
          }
        }
      }

      .preview-area {
        flex: 1;
        min-width: 0;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 15px;
        overflow-y: auto;
        background-color: #fff;

        .preview {
          h1, h2, h3, h4, h5, h6 {
            margin-top: 1em;
            margin-bottom: 0.5em;
            font-weight: bold;
            color: #333;
          }

          h1 { font-size: 2em; border-bottom: 1px solid #eee; }
          h2 { font-size: 1.5em; border-bottom: 1px solid #eee; }
          h3 { font-size: 1.25em; }

          p {
            margin: 0 0 1em;
            line-height: 1.6;
          }

          ul, ol {
            padding-left: 2em;
            margin-bottom: 1em;
          }

          blockquote {
            margin: 0 0 1em;
            padding: 0 1em;
            color: #6a737d;
            border-left: 0.25em solid #dfe2e5;
          }

          pre {
            background-color: #f6f8fa;
            border-radius: 3px;
            padding: 16px;
            overflow: auto;
            margin-bottom: 1em;

            code {
              background-color: transparent;
              padding: 0;
            }
          }

          code {
            background-color: rgba(27, 31, 35, 0.05);
            border-radius: 3px;
            padding: 0.2em 0.4em;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 85%;
          }

          table {
            border-collapse: collapse;
            margin-bottom: 1em;
            width: 100%;

            th, td {
              border: 1px solid #dfe2e5;
              padding: 6px 13px;
            }

            th {
              background-color: #f6f8fa;
              font-weight: bold;
            }

            tr:nth-child(2n) {
              background-color: #f6f8fa;
            }
          }

          img {
            max-width: 100%;
          }

          a {
            color: #0366d6;
            text-decoration: none;

            &:hover {
              text-decoration: underline;
            }
          }

          hr {
            height: 1px;
            margin: 1em 0;
            background-color: #e1e4e8;
            border: 0;
          }
        }
      }
    }

    .status-bar {
      margin-top: 15px;
      padding-top: 10px;
      border-top: 1px solid #ebeef5;
      font-size: 12px;
      color: #909399;
      display: flex;
      gap: 15px;
    }

    .draft-list {
      padding: 10px;

      .draft-item {
        padding: 12px;
        margin-bottom: 10px;
        border-radius: 4px;
        border: 1px solid #ebeef5;
        cursor: pointer;
        transition: all 0.3s;
        position: relative;

        &:hover {
          background-color: #f5f7fa;
          border-color: #dcdfe6;
        }

        .draft-title {
          font-weight: bold;
          margin-bottom: 6px;
          display: flex;
          justify-content: space-between;
        }

        .draft-time {
          font-size: 12px;
          color: #909399;
          font-weight: normal;
        }

        .draft-preview {
          font-size: 13px;
          color: #666;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .draft-actions {
          position: absolute;
          right: 10px;
          top: 10px;
          opacity: 0;
          transition: opacity 0.3s;
        }

        &:hover .draft-actions {
          opacity: 1;
        }
      }
    }
  }
}
</style>
